<script setup lang="ts">
  import axios from 'axios'
  // import { chunk } from 'lodash'
  import SparkMd5 from 'spark-md5'
  const onHttpRequest = async (e: any) => {
    const fileHash = await getFileHash(e.file)
    // console.log('fileHash:' + fileHash)

    const file = e.file
    // 每块分割大小
    const chunkSize = 1024 * 5
    // 切割次数
    const chunkCount = Math.ceil(file.size / chunkSize)
    // 文件切片 不是数组的slice 文件对象原型上的slice方法,继承自 Blob的slice 二进制数据
    // 创建一个FormData对象来存储文件片段和相关信息
    const formData = new FormData()
    for (let i = 0; i < chunkCount; i++) {
      const chunk = file.slice(i * chunkSize, i * chunkSize + chunkSize)
      const chunkHash = await getFileHash(file)
      formData.append('chunks', chunk, `${fileHash}:${chunkHash}`)
    }
    uploadChunk(formData)
  }
  const uploadChunk = async (formData: any) => {
    // console.log(formData)
    const chunk = formData.getAll('chunks')
    // console.log(chunk)
    for (let i = 0; i < chunk.length; i++) {
      await axios({
        method: 'post',
        url: '/upload',
        data: chunk[i],
      })
    }
    await axios({
      method: 'get',
      url: 'merge',
    })
  }

  // 封装获取hash的方法
  const getFileHash = async (file: any) => {
    const buffer = await fileParse(file)
    // 创建spark实例
    const spark = new SparkMd5.ArrayBuffer()
    // 将buffer数据处理为hash
    spark.append(buffer as any)
    // 返回hash
    return spark.end()
  }
  // 封装获取文件buffer的方法
  const fileParse = (file: any) => {
    return new Promise((resolve: any) => {
      // 创建读取文件的实例对象
      const fileReade = new FileReader()
      // 借助实例对象的方法读取文件流数据
      fileReade.readAsArrayBuffer(file)
      fileReade.onload = (res) => {
        // res.target.result 就是文件流数据
        resolve(res.target?.result)
      }
    })
  }
</script>

<template>
  <div class="large">
    <el-upload class="upload-demo" action="#" :http-request="onHttpRequest">
      <el-button size="small" type="primary">点击上传</el-button>
    </el-upload>
  </div>
</template>

<style lang="scss" scoped>
  @import './large.scss';
</style>
